package websocket.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import org.apache.log4j.Logger;
import org.util.digest.EncryptionArithmetic;
import org.zhc.annotation.Action;
import org.zhc.annotation.ActionClass;
import org.zhc.annotation.Property;
import org.zhc.annotation.ResponseType;
import org.zhc.annotation.Result;
import org.zhc.annotation.Results;
import org.zhc.context.ActionContext;

import websocket.pojo.Users;
import websocket.service.impl.UserService;

@ActionClass
public class RegisAction {

	private static final Logger logger = Logger.getLogger(RegisAction.class
			.getName());
	private Users user;
	private String mail;
	private Long uid;

	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}

	public String getMail() {
		return mail;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	public Long getUid() {
		return uid;
	}

	public void setUid(Long uid) {
		this.uid = uid;
	}

	@Action(name = "ValidateMail", namespace = "/servlet", param = { "mail" }, attribute = {})
	public String validate() {
		UserService service = new UserService();
		PrintWriter out = null;
		try {
			out = ActionContext.getContext(this).getResponse().getWriter();
			Integer mess = service.validateMail(mail) ? 1 : 0;
			out.print(mess);
		} catch (IOException e) {
			logger.error(e.getMessage());
		} finally {
			out.flush();
		}
		return null;
	}

	@Action(name = "Regis", namespace = "/servlet")
	@Results(@Result(location = "/regisRes.jsp", value = "success", type = ResponseType.REDIRECT, property = { @Property(name = "uid", value = "${uid}") }))
	public String regis() {
		UserService service = new UserService();
		this.uid = UserService.productUniqueNum();
		this.user.setUid(uid);
		this.user
				.setPassword(new EncryptionArithmetic(
						EncryptionArithmetic.SHA_256).getDigest(this.user
						.getPassword()));
		if (!service.insert(user)) {
			uid = null;
		} else {
			service.createDefGroup(uid);
		}
		return "success";
	}
}
